package com.ruoyi.waterManagement.service.impl;

import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.ruoyi.common.core.domain.business.waterManagement.WrStatvolD;
import com.ruoyi.common.core.domain.business.waterManagement.WrStatvolH;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.utils.business.BusinessUtils;
import com.ruoyi.waterManagement.domain.vo.NzrWrStatvolDVO;
import com.ruoyi.waterManagement.domain.vo.RzsWrStatvolHwrVO;
import com.ruoyi.waterManagement.domain.vo.WaterReportVO;
import com.ruoyi.waterManagement.domain.vo.YzrWrStatvolDVO;
import com.ruoyi.waterManagement.mapper.WrStatvolDMapper;
import com.ruoyi.waterManagement.mapper.WrStatvolHMapper;
import com.ruoyi.waterManagement.service.IWrStatvolDService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.DataFormat;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;


/**
 * 测站日水量Service业务层处理
 * 
 * @author hwd
 * @date 2023-02-20
 */
@Service
public class WrStatvolDServiceImpl implements IWrStatvolDService
{
    @Autowired
    private WrStatvolDMapper wrStatvolDMapper;
    @Autowired
    private WrStatvolHMapper wrStatvolHMapper;

    /**
     * 查询测站日水量
     * 
     * @param statCd 测站日水量主键
     * @return 测站日水量
     */
    @Override
    public WrStatvolD selectWrStatvolDByStatCd(String statCd)
    {
        return wrStatvolDMapper.selectWrStatvolDByStatCd(statCd);
    }

    /**
     * 查询测站日水量列表
     * 
     * @param wrStatvolD 测站日水量
     * @return 测站日水量
     */
    @Override
    public List<WrStatvolD> selectWrStatvolDList(WrStatvolD wrStatvolD)
    {
        if (wrStatvolD.getStatDay()!=null){
        String [] strings= DateUtils.jsYmd(wrStatvolD.getStatDay());
        String yy =strings[0];
        String mm =strings[1];
        wrStatvolD.setYy(yy);
        wrStatvolD.setMm(mm);
        }
        return wrStatvolDMapper.selectWrStatvolDList(wrStatvolD);
    }

    /**
     * 新增测站日水量
     * 
     * @param wrStatvolD 测站日水量
     * @return 结果
     */
    @Override
    public int insertWrStatvolD(WrStatvolD wrStatvolD)
    {
        return wrStatvolDMapper.insertWrStatvolD(wrStatvolD);
    }

    /**
     * 修改测站日水量
     * 
     * @param wrStatvolD 测站日水量
     * @return 结果
     */
    @Override
    public int updateWrStatvolD(WrStatvolD wrStatvolD)
    {
        return wrStatvolDMapper.updateWrStatvolD(wrStatvolD);
    }

    /**
     * 批量删除测站日水量
     * 
     * @param statCds 需要删除的测站日水量主键
     * @return 结果
     */
    @Override
    public int deleteWrStatvolDByStatCds(String[] statCds)
    {
        return wrStatvolDMapper.deleteWrStatvolDByStatCds(statCds);
    }

    /**
     * 删除测站日水量信息
     * 
     * @param statCd 测站日水量主键
     * @return 结果
     */
    @Override
    public int deleteWrStatvolDByStatCd(String statCd)
    {
        return wrStatvolDMapper.deleteWrStatvolDByStatCd(statCd);
    }

    @Override
    public List<YzrWrStatvolDVO> selectYzrWrStatvolDVOList(YzrWrStatvolDVO yzrWrStatvolDVO) {
        return wrStatvolDMapper.selectYzrWrStatvolDVOList(yzrWrStatvolDVO);
    }

    @Override
    public HashMap selectNzrWrStatvolDVO(NzrWrStatvolDVO nzrWrStatvolDVO) {
        BigDecimal ymax=new BigDecimal(0); //年度最大水量
        BigDecimal ymin=new BigDecimal(0); //年度最小水量
        Date yDatemax=null;   //年度最大水量日期
        Date yDatemin=null;   //年度最小水量日期
        BigDecimal allyv=new BigDecimal(0); //年度值
        int allycount=0; //年度供水天数
        HashMap<String,Object> ymap=new HashMap<>(); //记录年度信息map:
        ArrayList<NzrWrStatvolDVO> alllist=new ArrayList<>();//记录本月的list

        /**
         * 首先查询出当年该测站的所有数据
         */
        //判断参数是否完整，必须有查询的渠道code
        if(nzrWrStatvolDVO!=null&& StringUtils.isNotEmpty(nzrWrStatvolDVO.getStatCd())){
            //拆分数据，分成12个月分别统计
            for(int i=1;i<13;i++){
                HashMap<String,Object> resultmap=new HashMap<>();
//                ArrayList<NzrWrStatvolDVO> monlist=new ArrayList<>();//记录本月的list
                BigDecimal mmax=new BigDecimal(0);
                BigDecimal mmin=new BigDecimal(0);
                Date mDatemax=null;
                Date mDatemin=null;
                BigDecimal allv=new BigDecimal(0);
//                HashMap<String,NzrWrStatvolDVO> dateTOlist=new HashMap();
                //逐个修改
                nzrWrStatvolDVO.setQueryDate(DateUtils.parseDate(nzrWrStatvolDVO.getYy()+"-"+StringUtils.leftPad(i+"",2,'0')+"-01"));
                List<NzrWrStatvolDVO> allnzrlist=wrStatvolDMapper.selectNzrWrStatvolDVO(nzrWrStatvolDVO);
                //拿到当月
                for(NzrWrStatvolDVO tmp:allnzrlist){
                    allv=allv.add(tmp.getDayVol());
//                    dateTOlist.put(DateFormatUtils.format(tmp.getDT(),"MM-dd"),tmp);
                    tmp.setStatMark(DateFormatUtils.format(tmp.getStatDay(),"MM_d"));
                    //判断当月最大最小值
                    if(mmax.compareTo(tmp.getDayVol())==-1){
                        //比tmpvalue大直接放入最大
                        mmax=tmp.getDayVol();
                        mDatemax=tmp.getStatDay();
                    }
                    if(mmin.compareTo(new BigDecimal(0))==0){
                        mmin=tmp.getDayVol();
                        mDatemin=tmp.getStatDay();
                    }else if((tmp.getDayVol().compareTo(mmin)==-1)){
                        mmin=tmp.getDayVol();
                        mDatemin=tmp.getStatDay();
                    }
                }
                resultmap.put("mmax",mmax); //月最大值
                resultmap.put("mmin",mmin);//月最小值
                resultmap.put("mDatemax",mDatemax==null?"":DateUtils.parseDateToStr("MM月dd日",mDatemax)); //月最大日期
                resultmap.put("mDatemin",mDatemin==null?"":DateUtils.parseDateToStr("MM月dd日",mDatemin));//月最小日期
                resultmap.put("mavg", CollectionUtils.isEmpty(allnzrlist)?0:allv.divide(new BigDecimal(allnzrlist.size()),3));//计算月平均
                resultmap.put("days",allnzrlist.size());
                alllist.addAll(allnzrlist);
                if(ymax.compareTo(mmax)==-1){
                    //比tmpvalue大直接放入最大
                    ymax=mmax;
                    yDatemax=mDatemax;
                }
                if(ymin.compareTo(new BigDecimal(0))==0){
                    ymin=mmin;
                    yDatemin=mDatemin;
                }else if((mmin.compareTo(new BigDecimal(0))==1)&&(ymin.compareTo(mmin)==1)){
                    ymin=mmin;
                    yDatemin=mDatemin;
                }

                allyv=allyv.add(allv);
                allycount+=allnzrlist.size();
                ymap.put("l"+i,resultmap);
            }
            ymap.put("alllist",alllist);
            ymap.put("ymax",ymax);
            ymap.put("ymin",ymin);
            ymap.put("yDatemax",yDatemax==null?"":DateUtils.parseDateToStr("MM月dd日",yDatemax));
            ymap.put("yDatemin",yDatemin==null?"":DateUtils.parseDateToStr("MM月dd日",yDatemin));
            ymap.put("allycount",allycount);
            ymap.put("allyv",allyv);
            ymap.put("yavg",allycount==0?0:allyv.divide(new BigDecimal(allycount),3));
        }
        return ymap;

    }

    @Override
    public HashMap selectNzrWaterLevelVO(NzrWrStatvolDVO nzrWrStatvolDVO) {

            BigDecimal ymax=new BigDecimal(0); //年度最大水位
            BigDecimal ymin=new BigDecimal(0); //年度最小水位
            Date yDatemax=null;   //年度最大水位日期
            Date yDatemin=null;   //年度最小水位日期
            BigDecimal allyv=new BigDecimal(0); //年度值
            int allycount=0; //年度供水天数
            HashMap<String,Object> ymap=new HashMap<>(); //记录年度信息map:
            ArrayList<NzrWrStatvolDVO> alllist=new ArrayList<>();//记录本月的list

            /**
             * 首先查询出当年该测站的所有数据
             */
            //判断参数是否完整，必须有查询的渠道code
            if(nzrWrStatvolDVO!=null&& StringUtils.isNotEmpty(nzrWrStatvolDVO.getStatCd())){
                //拆分数据，分成12个月分别统计
                for(int i=1;i<13;i++){
                    HashMap<String,Object> resultmap=new HashMap<>();
//                ArrayList<NZRWaterVO> monlist=new ArrayList<>();//记录本月的list
                    BigDecimal mmax=new BigDecimal(0);
                    BigDecimal mmin=new BigDecimal(0);
                    Date mDatemax=null;
                    Date mDatemin=null;
                    BigDecimal allv=new BigDecimal(0);
//                HashMap<String,NZRWaterVO> dateTOlist=new HashMap();
                    //逐个修改
                    nzrWrStatvolDVO.setQueryDate(DateUtils.parseDate(nzrWrStatvolDVO.getYy()+"-"+StringUtils.leftPad(i+"",2,'0')+"-01"));
                    List<NzrWrStatvolDVO> allnzrlist=wrStatvolDMapper.selectNzrWaterLevelVO(nzrWrStatvolDVO);
                    //拿到当月
                    for(NzrWrStatvolDVO tmp:allnzrlist){
                        allv=allv.add(tmp.getDayLevel());
//                    dateTOlist.put(DateFormatUtils.format(tmp.getDT(),"MM-dd"),tmp);
                        tmp.setStatMark(DateFormatUtils.format(tmp.getStatDay(),"MM_d"));
                        //判断当月最大最小值
                        if(mmax.compareTo(tmp.getDayLevel())==-1){
                            //比tmpvalue大直接放入最大
                            mmax=tmp.getDayLevel();
                            mDatemax=tmp.getStatDay();
                        }
                        if(mmin.compareTo(new BigDecimal(0))==0){
                            mmin=tmp.getDayLevel();
                            mDatemin=tmp.getStatDay();
                        }else if((tmp.getDayLevel().compareTo(mmin)==-1)){
                            mmin=tmp.getDayLevel();
                            mDatemin=tmp.getStatDay();
                        }
                    }
                    resultmap.put("mmax",mmax); //月最大值
                    resultmap.put("mmin",mmin);//月最小值

                    resultmap.put("mDatemax",mDatemax==null?"":DateUtils.parseDateToStr("MM月dd日",mDatemax)); //月最大日期
                    resultmap.put("mDatemin",mDatemin==null?"":DateUtils.parseDateToStr("MM月dd日",mDatemin));//月最小日期
                    resultmap.put("mavg", CollectionUtils.isEmpty(allnzrlist)?0:allv.divide(new BigDecimal(allnzrlist.size()),3));//计算月平均
                    resultmap.put("days",allnzrlist.size());
                    alllist.addAll(allnzrlist);
                    if(ymax.compareTo(mmax)==-1){
                        //比tmpvalue大直接放入最大
                        ymax=mmax;
                        yDatemax=mDatemax;
                    }
                    if(ymin.compareTo(new BigDecimal(0))==0){
                        ymin=mmin;
                        yDatemin=mDatemin;
                    }else if((mmin.compareTo(new BigDecimal(0))==1)&&(ymin.compareTo(mmin)==1)){
                        ymin=mmin;
                        yDatemin=mDatemin;
                    }

                    allyv=allyv.add(allv);
                    allycount+=allnzrlist.size();
                    ymap.put("l"+i,resultmap);
                }
                ymap.put("alllist",alllist);
                ymap.put("ymax",ymax);
                ymap.put("ymin",ymin);
                ymap.put("yDatemax",yDatemax==null?"":DateUtils.parseDateToStr("MM月dd日",yDatemax));
                ymap.put("yDatemin",yDatemin==null?"":DateUtils.parseDateToStr("MM月dd日",yDatemin));
                ymap.put("allycount",allycount);
                ymap.put("allyv",allyv);
                ymap.put("yavg",allycount==0?0:allyv.divide(new BigDecimal(allycount),3));
            }
            return ymap;



    }

    @Override
    public HashMap selectNzrFlowVO(NzrWrStatvolDVO nzrWrStatvolDVO) {
            BigDecimal ymax=new BigDecimal(0); //年度最大流量
            BigDecimal ymin=new BigDecimal(0); //年度最小流量
            Date yDatemax=null;   //年度最大流量日期
            Date yDatemin=null;   //年度最小流量日期
            BigDecimal allyv=new BigDecimal(0); //年度值
            int allycount=0; //年度供水天数
            HashMap<String,Object> ymap=new HashMap<>(); //记录年度信息map:
            ArrayList<NzrWrStatvolDVO> alllist=new ArrayList<>();//记录本月的list

            /**
             * 首先查询出当年该测站的所有数据
             */
            //判断参数是否完整，必须有查询的渠道code
            if(nzrWrStatvolDVO!=null&& StringUtils.isNotEmpty(nzrWrStatvolDVO.getStatCd())){
                //拆分数据，分成12个月分别统计
                for(int i=1;i<13;i++){
                    HashMap<String,Object> resultmap=new HashMap<>();
//                ArrayList<NZRWaterVO> monlist=new ArrayList<>();//记录本月的list
                    BigDecimal mmax=new BigDecimal(0);
                    BigDecimal mmin=new BigDecimal(0);
                    Date mDatemax=null;
                    Date mDatemin=null;
                    BigDecimal allv=new BigDecimal(0);
//                HashMap<String,NZRWaterVO> dateTOlist=new HashMap();
                    //逐个修改
                    nzrWrStatvolDVO.setQueryDate(DateUtils.parseDate(nzrWrStatvolDVO.getYy()+"-"+StringUtils.leftPad(i+"",2,'0')+"-01"));
                    List<NzrWrStatvolDVO> allnzrlist=wrStatvolDMapper.selectNzrFlowVO(nzrWrStatvolDVO);
                    //拿到当月
                    for(NzrWrStatvolDVO tmp:allnzrlist){
                        allv=allv.add(tmp.getDayFlow());
//                    dateTOlist.put(DateFormatUtils.format(tmp.getDT(),"MM-dd"),tmp);
                        tmp.setStatMark(DateFormatUtils.format(tmp.getStatDay(),"MM_d"));
                        //判断当月最大最小值
                        if(mmax.compareTo(tmp.getDayFlow())==-1){
                            //比tmpvalue大直接放入最大
                            mmax=tmp.getDayFlow();
                            mDatemax=tmp.getStatDay();
                        }
                        if(mmin.compareTo(new BigDecimal(0))==0){
                            mmin=tmp.getDayFlow();
                            mDatemin=tmp.getStatDay();
                        }else if((tmp.getDayFlow().compareTo(mmin)==-1)){
                            mmin=tmp.getDayFlow();
                            mDatemin=tmp.getStatDay();
                        }
                    }
//                for(int j=1;j<32;j++){
//                    //不存在的增加一个0
//                    if(!dateTOlist.containsKey(i+"-"+j)){
//                        NZRWaterVO tmp=new NZRWaterVO();
//                        tmp.setV(new BigDecimal(0));
//                        tmp.setDT(DateUtils.parseDate(nzrWaterVO.getYear()+"-"+StringUtils.leftPad(i+"",2,'0')+"-"+StringUtils.leftPad(j+"",2,'0')));
//                        monlist.add(tmp);
//                    }else{
//                        monlist.add(dateTOlist.get(i+"-"+j));
//                    }
//                }
                    resultmap.put("mmax",mmax); //月最大值
                    resultmap.put("mmin",mmin);//月最小值
                    resultmap.put("mDatemax",mDatemax==null?"":DateUtils.parseDateToStr("MM月dd日",mDatemax)); //月最大日期
                    resultmap.put("mDatemin",mDatemin==null?"":DateUtils.parseDateToStr("MM月dd日",mDatemin));//月最小日期
                    resultmap.put("mavg", CollectionUtils.isEmpty(allnzrlist)?0:allv.divide(new BigDecimal(allnzrlist.size()),3));//计算月平均
                    resultmap.put("days",allnzrlist.size());
                    alllist.addAll(allnzrlist);
                    if(ymax.compareTo(mmax)==-1){
                        //比tmpvalue大直接放入最大
                        ymax=mmax;
                        yDatemax=mDatemax;
                    }
                    if(ymin.compareTo(new BigDecimal(0))==0){
                        ymin=mmin;
                        yDatemin=mDatemin;
                    }else if((mmin.compareTo(new BigDecimal(0))==1)&&(ymin.compareTo(mmin)==1)){
                        ymin=mmin;
                        yDatemin=mDatemin;
                    }

                    allyv=allyv.add(allv);
                    allycount+=allnzrlist.size();
                    ymap.put("l"+i,resultmap);
                }
                ymap.put("alllist",alllist);
                ymap.put("ymax",ymax);
                ymap.put("ymin",ymin);
                ymap.put("yDatemax",yDatemax==null?"":DateUtils.parseDateToStr("MM月dd日",yDatemax));
                ymap.put("yDatemin",yDatemin==null?"":DateUtils.parseDateToStr("MM月dd日",yDatemin));
                ymap.put("allycount",allycount);
                ymap.put("allyv",allyv);
                ymap.put("yavg",allycount==0?0:allyv.divide(new BigDecimal(allycount),3));
            }
            return ymap;
    }

    @Override
    public List<WaterReportVO> selectDayWaterReport(WaterReportVO waterReportVO) {

        return listDailyWaterReport(waterReportVO);
    }

    @Override
    public void exportExcel(WaterReportVO waterReportVO, HttpServletResponse response, String excelTitle) throws IOException {

        InputStream inputStream = null;
        List<WaterReportVO> list = null;
        WaterReportVO sumVO = null;
        inputStream = this.getClass().getClassLoader().getResourceAsStream("static/file/水量日报.xlsx");
        list = listDailyWaterReport(waterReportVO);
//        sumVO = this.selectWrPlanMonRiunSum(wrPlanMonRiun);

        List<WaterReportVO> result = new ArrayList<>();
        int k = 0;
        // 添加序号
//        for(int i = 1; i <= list.size(); i++) {
//            WaterReportVO entity = list.get(i - 1);
//            entity.setOrder(String.valueOf(i));
//            k++;
//        }
        result.addAll(list);

//        // 添加合计
//        if(null != sumVO) {
//            sumVO.setRiunName("合计");
//            sumVO.setOrder(String.valueOf(k + 1));
//            result.add(sumVO);
//        }

        // 添加表头和日期
        Map<String, String> map = new HashMap<>();
        map.put("excelTitle", excelTitle);
        Date now = new Date();
        String nowDateStr = DateFormatUtils.format(now, "yyyy年MM月dd日");
        map.put("nowDate", nowDateStr);
        ServletOutputStream out = response.getOutputStream();
        ExcelWriter excelWriter = EasyExcel.write(out, WaterReportVO.class).withTemplate(inputStream).build();
        WriteSheet writeSheet = EasyExcel.writerSheet().build();
        excelWriter.fill(result, writeSheet);
        excelWriter.fill(map, writeSheet);
        excelWriter.finish();
    }


    public List<WaterReportVO> listDailyWaterReport (WaterReportVO dayWaterReportVO){
        /**入参水管机构 日期
         */
        //判断关键参数日期是否存在
        Date wrdate=dayWaterReportVO.getDd();
        if(wrdate !=null){
            //晚于当前日期或者没有日期，则改为当前日期
        }else{
            wrdate=new Date();
        }
        dayWaterReportVO.setDd(wrdate);
        if (StringUtils.isEmpty(dayWaterReportVO.getOrgCd())) {
            dayWaterReportVO.setOrgCd(null);
        }
        //找到下属的所有水管机构的统计
        HashMap<String, Object> addvAndOrgCodeInfo = BusinessUtils.getAddvAndOrgCodeInfo(dayWaterReportVO.getOrgCd());
        int grade = (int) addvAndOrgCodeInfo.get("grade");
        String resCode = (String) addvAndOrgCodeInfo.get("resCode");
        dayWaterReportVO.setOrgCd(resCode+"%");
        List<WaterReportVO> dayWaterReportList = wrStatvolDMapper.selectDayWaterReport(dayWaterReportVO);
        if (grade == 1){
            //查找下属水管机构
            resCode =  resCode + "%0000";
        }else if (grade == 2) {
            //查找下属水管机构
            resCode =resCode + "%00";
        }else if(grade ==3) {
            resCode =resCode+"%";
        }else {
            resCode = resCode;
        }
        //查找下属机构
        RzsWrStatvolHwrVO rzsWrStatvolHwrVO=new RzsWrStatvolHwrVO();
        rzsWrStatvolHwrVO.setOrgCd(resCode);
        List<RzsWrStatvolHwrVO> orglist = wrStatvolHMapper.listOrgCd(rzsWrStatvolHwrVO);
        List<WaterReportVO> orgnewList =new ArrayList<>();
        //遍历查询下属水管机构统计
        for (RzsWrStatvolHwrVO r:orglist
        ) {
            HashMap<String, Object> stringObjectHashMap = BusinessUtils.getAddvAndOrgCodeInfo(r.getOrgCd());
            String ro = (String) stringObjectHashMap.get("resCode");
            List<WaterReportVO> dayWaterReportVOList = dayWaterReportList.stream().filter(s -> s.getOrgCd().startsWith(ro)).collect(Collectors.toList());
            WaterReportVO wrVoSum =new WaterReportVO();
            BigDecimal dayWaterVol =new BigDecimal("0");
            wrVoSum.setOrgNm(r.getOrgNm());
            if (dayWaterReportVOList.size()>0) {
                for (WaterReportVO w : dayWaterReportVOList
                ) {
                    dayWaterVol = w.getDayVol() == null ? dayWaterVol.add(new BigDecimal("0")) : dayWaterVol.add(w.getDayVol()).setScale(4, BigDecimal.ROUND_HALF_UP);
                }
            }
            wrVoSum.setOrgCd("合计");
            wrVoSum.setDayVol(dayWaterVol);
            orgnewList.add(0,wrVoSum);
        }
        orgnewList.removeAll(Collections.singleton(null));
        //将数据结果放入map中区分时
        Collections.reverse(orgnewList);
        return orgnewList;
}

}
